﻿using System;
using System.Text;

namespace mfLogger
{
    public class mfLogMessage : IDisposable
    {
        #region CTOR

        public mfLogMessage(string text)
        {
            TimeStamp = DateTime.Now;
            Level = enumLogMessageLevel.Info;
            Text = text;
        }

        public mfLogMessage(enumLogMessageLevel level, string text) 
        {
            TimeStamp = DateTime.Now;
            Level = level;
            Text = text;
        }

        public mfLogMessage(Exception ex)
        {
            TimeStamp = DateTime.Now;
            Level = enumLogMessageLevel.Error;

            Text = ExtractMessage(ex);
        }
        #endregion

        #region Properties

        public DateTime TimeStamp { get; private set; }

        public String Text { get; set; }

        public enumLogMessageLevel Level { get; set; }

        #endregion

        #region Methods
        public static String TranslateEndSensorType(enumLogMessageLevel msgLevel)
        {
            switch (msgLevel)
            {
                case enumLogMessageLevel.Debug:
                    return "Debug";
                case enumLogMessageLevel.Info:
                    return "Info";
                case enumLogMessageLevel.Warning:
                    return "Warning";
                case enumLogMessageLevel.Error:
                    return "Error";
                default:
                    return "n.def.";
            }
        }

        private static string ExtractMessage(Exception ex)
        {
            var strEx = new StringBuilder();

            strEx.AppendLine(ex.Message);
            strEx.AppendLine("Stacktrace:");
            strEx.AppendLine(ex.StackTrace);

            if (ex.InnerException != null)
            {
                strEx.Append(ex.InnerException);
            }

            return strEx.ToString();
        }

        public override string ToString()
        {
            return TimeStamp + " (" + TranslateEndSensorType(Level) + "): " + Text;
        }

        public override int GetHashCode()
        {
            return ToString().GetHashCode();
        }
        #endregion

        #region IDisposable
        public void Dispose()
        {
            Text = null;
        } 
        #endregion
    }
}
